package com.feimt.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.feimt.common.R;
import com.feimt.common.SMSSendCode;
import com.feimt.pojo.User;
import com.feimt.service.UserService;
import com.feimt.utils.CodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        log.info("user:{}",user);
        /*1. 生成验证码 随机数 4*/
        String code = CodeUtils.generateValidateCode(4).toString();
        log.info("code:{}",code);

        /*2. 验证码 存会话 才能在登录的时候比较验证码*/
//        session.setAttribute("code:"+user.getPhone(),code);
        redisTemplate.opsForValue().set("code:"+user.getPhone(),code,5, TimeUnit.MINUTES);


        /*3. 调用阿里巴巴发送短信*/
//        try {
//            SMSSendCode.sendCode(user.getPhone(),code.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

        return R.success(code);
    }
    @Autowired
    private UserService userService;

    @PostMapping("login")
    public R login(@RequestBody Map<String,String> map,HttpSession session){
        //1. 比较验证码
        // 用户输入的
        String code = map.get("code");
        String phone = map.get("phone");
        // 会话存的
//        String sessionCode = (String) session.getAttribute("code:" + phone);
        String sessionCode = (String) redisTemplate.opsForValue().get("code:" + phone);


        if(code == null||!sessionCode.equals(code)){
            System.out.println("验证码输入错误");
            return R.error("验证码输入错误");
        }

        // redis删除验证码
        redisTemplate.delete("code:" + phone);

        LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>();
        qw.eq(User::getPhone,phone);
        User one = userService.getOne(qw);
        if(one != null){
            //2. 手机号存在 - 登录
            //存会话
            session.setAttribute("auth",one.getId());
            return R.success(one);//回显
        }else {
            //3. 手机号不存在 - 注册
            User user = new User();
            user.setName("user_"+phone);
            user.setPhone(phone);
            userService.save(user);
            //存会话
            session.setAttribute("auth",user.getId());
            return R.success(user);//回显
        }
    }

}
